const mongoose = require('mongoose');

const universitySchema = new mongoose.Schema({
  schoolName: {
    type: String,
    required: [true, '学校名称为必填项'],
    unique: true,
    trim: true
  },
  schoolCode: {
    type: String,
    required: [true, '学校标准码为必填项'],
    unique: true,
    trim: true
  },
  governingDepartment: {
    type: String,
    enum: ['教育部', '工信部', '省教育厅', '其他']
  },
  location: {
    type: String,
    enum: ['北京', '上海', '广东', '江苏', '其他']
  },
  isCentral: {
    type: Boolean,
    required: [true, '是否中央直属为必填项'],
    default: false
  },
  contactDepartment: {
    type: String,
    trim: true
  },
  contactPosition: {
    type: String,
    trim: true
  },
  contactName: {
    type: String,
    required: [true, '联系人姓名为必填项'],
    trim: true
  },
  landlinePhone: {
    type: String,
    required: [true, '座机号码为必填项'],
    trim: true,
    validate: {
      validator: function(v) {
        return /^(\d{3,4}-?)?\d{7,8}$/.test(v);
      },
      message: '请输入有效的座机号码'
    }
  },
  mobilePhone: {
    type: String,
    required: [true, '手机号码为必填项'],
    trim: true,
    validate: {
      validator: function(v) {
        return /^1[3-9]\d{9}$/.test(v);
      },
      message: '请输入有效的手机号码'
    }
  },
  remarks: {
    type: String,
    trim: true
  }
}, {
  timestamps: true,
  toJSON: { virtuals: true },
  toObject: { virtuals: true }
});

// 虚拟字段：关联的授课计划数量
universitySchema.virtual('planCount', {
  ref: 'Plan',
  localField: '_id',
  foreignField: 'universityId',
  count: true
});

// 索引 (schoolName字段已通过unique:true自动创建索引)
universitySchema.index({ location: 1 });
universitySchema.index({ isCentral: 1 });

module.exports = mongoose.model('University', universitySchema);
